本來想加入Openlayers( https://openlayers.org/ ) (version 7.4.0 )已全面改用JavaScript ES6,還不會建置ES6環境
故先利用Visual Studio 2022預設範例"搭配React.js的ASP.NET CORE"(React.js SPA搭配.NET Core API),React.js也是ES6,ES6的開發環境就出來了~
A. NavItem加上Map連結
B. Approutes加上Map連結
C. 新增Map.js
import React, { Component } from 'react';
export class Map extends Component {
render() {
return <div>test....</div>
}
}
在ClientApp資料夾下打開cmd,並執行npm i ol
執行成功後可看package.json多一個"ol",以及多一個"ol"資料夾
4.根據官方QuickStart範例( https://openlayers.org/doc/quickstart.html ),Create OpenLayer.js
import React, { useEffect } from "react";
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/Tile.js';
import View from 'ol/View.js';
import './OpenLayer.css';
function OpenLayer() {
useEffect(() => {
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
});
return (
<div id="map" className="map-container" />
);
}
export default OpenLayer;
5.Create OpenLayer.css,注意大寫小,寫錯可是不行的
.map-container {
height: 100vh;
width: 100%;
}
6.在原本的Map.js,新增剛剛做好的
import React, { Component } from 'react';
import OpenLayer from './OpenLayer'
export class Map extends Component {
render() {
return <OpenLayer />;
}
}
7.執行程式,大功告成